<template>
	<view class="write-article" :style="{'min-height':winHeight +'px'}">
		
		<!-- 导航 -->
		<uni-nav-bar
		@clickLeft="goBack"
		left-icon="back"
		title="写文章 -- 简书"
		status-bar></uni-nav-bar>
		<!-- 标题 -->
		<view class="title">
			<input type="text" placeholder="点击输入标题" v-model="article.title" class="title-input" />
		</view>
		
		<!-- 动态添加的编辑块 -->
		<view class="edit-part">
			<editBlock v-for="t in txtEditor" :key="t.id" :txtEditor="t" @delOneBlock="delOneBlock"></editBlock>
		</view>
		
		<!-- 添加按钮 -->
		<view class="add-content" :style="{'margin-left':winWidth/2 + 'px'}"
		@click="popAdd">
			<button class="add-btn">+ 添加</button>
		</view>
		
		<view class="add-wrapper" :style="{'height':winHeight +'px'}" @click="hideModel" v-show="showAdd">
			<view class="options">
				<view class="add-txt" @click="addTxt">文字</view>
				<view class="add-img" @click="addImg">图片</view>
			</view>
		</view>
		
		
		<!-- 底部操作 -->
		<view class="bottom-operate">
			<view class="preview" @click="preview">预览</view>
			<view class="save-publish">保存并发布</view>
		</view>
	</view>
</template>

<script>
	import editBlock from '../../components/editBlock/editBlock.vue'
	import uniNavBar from "../../components/uni-nav-bar/uni-nav-bar.vue"
	import { mapMutations } from 'vuex'
	import { mapState } from 'vuex'
	
	export default {
		data() {
			return {
				article: {
					title: '',
				},
				winHeight:'',
				winWidth:'',
				showAdd:false,
				txtEditor:[],
				txtEditorId:0, //编辑器的id
				tmpImgPath:'', //临时图片文件路径
			}
			
		},
		methods: {
			...mapMutations(['delEditContent','addEditContent','clearEditContent']),
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},
			undo() {
				this.editorCtx.undo()
			},
			//弹出添加的选项 
			popAdd(){
				this.showAdd = true
			},
			// 隐藏模态框
			hideModel(){
				this.showAdd = false
			},
			// 添加文字
			addTxt(){
				let _this = this;
				this.txtEditor.push({
					id:_this.txtEditorId++,
					type:'txt'
				})
			},
			// 添加图片
			addImg(){
				let _this = this
				
				// 选择图片并上传
				new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album'], //从相册选择
						success: res => {
							
							
							const path = res.tempFilePaths[0]
							let ext
							uni.getImageInfo({
								src: path,
								success(info) {
									const options = {
										filePath: path,
										cloudPath: Date.now() + '.' + info.type.toLowerCase()
									}
									resolve(options)
								},
								fail(err) {
									reject(new Error(err.errMsg || '未能获取图片类型'))
								}
							})
						},
						fail: () => {
							reject(new Error('Fail_Cancel'))
						}
					})
				}).then((options) => {
					uni.showLoading({
						title: '文件上传中...'
					})
					return uniCloud.uploadFile({
						...options,
						onUploadProgress(e) {
							console.log(e)
						}
					})
				}).then(res => {
					
					_this.tmpImgPath = res.fileID;
					// 生成编辑器组件
					_this.txtEditor.push({
						id:_this.txtEditorId++,
						type:'img',
						src:_this.tmpImgPath,
						des:''
					})
					
					uni.hideLoading()
					uni.showModal({
						content: '图片上传成功',
						showCancel: false
					})
				}).catch((err) => {
					uni.hideLoading()
					if (err.message !== 'Fail_Cancel') {
						uni.showModal({
							content: `图片上传失败`,
							showCancel: false
						})
					}
				})
				
			},
			//删除一个编辑块 
			delOneBlock(content){
				console.log("删除：",content);
				this.delEditContent(content)
				
				for(let i=0;i<this.txtEditor.length;i++){
					if(this.txtEditor[i].id === content.id){
						this.txtEditor.splice(i,1);
						return;
					}
				}
			},
			// 验证输入
			volidateArticle(){
				if(this.article.title.trim().length === 0) {
					uni.showModal({
						content:'请输入标题',
						showCancel:false
					})
					return false;
				}else if(this.editContent.length+1 === 0){
					uni.showModal({
						content:'请输入正文',
						showCancel:false
					})
					return false;
				}else {
					return true
				}
			},
			//预览文章
			preview(){
				let _this = this;
				let flag = this.volidateArticle()
				if(!flag){
					return
				}
				// 跳转到预览的界面
				uni.navigateTo({
				    url: '../preview/preview?title=' + _this.article.title,
					animationType:'pop-in'
				});
			},
			// 导航返回上一级
			goBack(){
				uni.navigateBack({
					delta:1,
					animationType:'pop-out',
					animationDuration:300
				})
			}
		},
		components: {
			editBlock,
			uniNavBar
		},
		created() {
			// 清空store内编辑器的内容
			this.clearEditContent();
			let that = this
			uni.getSystemInfo({
				success(res) {
					that.winHeight = res.windowHeight
					that.winWidth = res.windowWidth
				}
			})
		},
		computed:{
			...mapState(['editContent'])
		}

	}
</script>

<style>
	.status_bar {
	    height: var(--status-bar-height);
	    width: 100%;
	}
	.write-article {
		padding-bottom: 100rpx;
		background-color: #f1f1f1;
	}
	.title {
		background-color: #fff;
		height: 100rpx;
		width: 100%;
		padding-left: 20rpx;
	}

	.title-input {
		height: 100%;
		line-height: 100rpx;
		font-size: 40rpx;
	}
	.add-content {
		transform: translateX(-50%);
		width: 20%;		
	}
	.add-btn {
		background-color: #fff;
		font-size: 20rpx;
		border-radius: 50rpx;
		color: #aaa;
		margin-top: 20rpx;
	}
	.add-wrapper {
		position: absolute;
		top: 0;
		left: 0;
		background-color: rgba(0,0,0,.6);
		width: 100%;
	}
	.options {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		background-color: #fff;
		border-radius: 10rpx;
		width: 50%;
		text-align: center;
		z-index: 999;
	}
	.add-img,
	.add-txt{
		line-height: 100rpx;
	}
	.add-img {
		border-bottom: 1px solid #ddd;
	}
	.bottom-operate {
		cursor: pointer;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		line-height: 100rpx;
		background-color: #fff;
		box-shadow: 0 -1px 15px #ddd;
		text-align: center;
		display: flex;
	}
	.preview {
		flex: 1;
	}
	.save-publish {
		flex: 1;
		background-color: #ff6811;
		color: #fff;
	}
</style>
